//
//  SearchLifeController.m
//  CenturyCity
//
//  Created by beisheng03 on 2018/1/16.
//  Copyright © 2018年 beisheng. All rights reserved.
//

#import "SearchLifeController.h"
#import "LifeServiceCell.h"
#import "LifeServiceModel.h"
#import "LifeNothingCell.h"

#import "AboutusController.h"

@interface SearchLifeController ()
@property (nonatomic, assign) NSInteger curpage;

@property (nonatomic, assign) NSString *pageCount;

@property (nonatomic, assign) NSString *totalCount;

@property (nonatomic, strong) NSMutableArray<LifeServiceModel *> *dataModels;

@end

@implementation SearchLifeController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.navigationItem.title = @"菲度锦囊";
    
    self.tableView.rowHeight = UITableViewAutomaticDimension;
    
    self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    
    self.tableView.estimatedRowHeight = 100;
    
    self.tableView.backgroundColor = viewBgGrey;
    
    [self.tableView registerNib:[UINib nibWithNibName:NSStringFromClass([LifeServiceCell class]) bundle:nil] forCellReuseIdentifier:[LifeServiceCell identifierStr]];
    
    [self.tableView registerNib:[UINib nibWithNibName:NSStringFromClass([LifeNothingCell class]) bundle:nil] forCellReuseIdentifier:[LifeNothingCell identifierStr]];
    
    MJWeakSelf
    self.tableView.mj_header = [XMGRefreshHeader headerWithRefreshingBlock:^{
        
        [weakSelf loadData];
        
    }];
    
    [weakSelf.tableView.mj_header beginRefreshing];
    
    
}


- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    
    [self.navigationController setNavigationBarHidden:NO animated:YES];
    
    
}


- (void)loadData{
    self.curpage = 1;
    
    NSMutableDictionary *parameters = [NSMutableDictionary dictionary];
    parameters[@"page"] = @"1";
    parameters[@"pagesize"] = @"20";
    parameters[@"keyword"] = self.keyword;

    //    keyword
    
    //    parameters[@"uid"] = myViewModel.user.uid;
    
    MJWeakSelf;
    [[NetworkTools shareNetworkTools]sendRequestWithHttpMethod:GET_METHOD URLPath:@"news/lists" parameters:parameters completionHandler:^(id responseObject, NSError *error) {
        
        if (!error) {
            
            MYJSONSTR
            
            //                    [[responseObject[@"data"][@"data"] firstObject]  propertyCode];
            
            weakSelf.pageCount = responseObject[@"data"][@"page_count"];
            
            weakSelf.totalCount = responseObject[@"data"][@"total_count"];
            
            
            weakSelf.dataModels = [LifeServiceModel mj_objectArrayWithKeyValuesArray:responseObject[@"data"][@"news"]];
            
            
            //                                    [weakSelf.dataModels removeAllObjects];
            ////
            ////
            //                                    weakSelf.totalCount = @"0";
            
            //            NSLog(@"%ld",weakSelf.dataModels.count);
            
            if ([weakSelf.totalCount isEqualToString:@"0"]) {
                
                [weakSelf.tableView.mj_header endRefreshing];
                
                [weakSelf.tableView reloadData];
                
            } else {
                
                [self cachePictures:weakSelf.dataModels];
                
                
            }
            
            
            
            
        } else {
            
            [weakSelf.tableView.mj_header endRefreshing];
            
            [SVProgressHUD showInfoWithStatus:error.domain];
            
        }
    }];
    
    
    
}


- (void)cachePictures:(NSMutableArray<LifeServiceModel *> *)models{
    
    
    dispatch_group_t group = dispatch_group_create();
    
    for (LifeServiceModel *model in self.dataModels) {
        
        
        
        dispatch_group_enter(group);
        
        
        [[SDWebImageManager sharedManager] downloadImageWithURL:[NSURL URLWithString:model.image] options:kNilOptions progress:nil completed:^(UIImage *image, NSError *error, SDImageCacheType cacheType, BOOL finished, NSURL *imageURL) {
            
            dispatch_group_leave(group);
            
        }];
        
        
        
    }
    
    
    MJWeakSelf;
    
    dispatch_group_notify(group, dispatch_get_main_queue(), ^{
        
        weakSelf.tableView.mj_footer = [XMGRefreshFooter footerWithRefreshingBlock:^{
            
            [weakSelf loadMoreData];
            
        }];
        
        [weakSelf.tableView.mj_footer resetNoMoreData];
        
        
        if ([weakSelf.pageCount isEqualToString:@"1"]) {
            
            [weakSelf.tableView.mj_footer endRefreshingWithNoMoreData];
            
        }
        
        
        [weakSelf.tableView.mj_header endRefreshing];
        
        
        
        [weakSelf.tableView reloadData];
        
        
    });
    
    
    
}






- (void)loadMoreData{
    
    self.curpage ++;
    
    NSMutableDictionary *parameters = [NSMutableDictionary dictionary];
    parameters[@"pagesize"] = @"20";
    parameters[@"page"] = [NSString stringWithFormat:@"%ld",(long)self.curpage];
    parameters[@"keyword"] = self.keyword;

    
    MJWeakSelf;
    [[NetworkTools shareNetworkTools] sendRequestWithHttpMethod:GET_METHOD URLPath:@"news/lists" parameters:parameters completionHandler:^(id responseObject, NSError *error) {
        
        if (!error) {
            
            NSMutableArray<LifeServiceModel *> *temp = [LifeServiceModel mj_objectArrayWithKeyValuesArray:responseObject[@"data"][@"news"]];
            
            
            
            
            [weakSelf.dataModels addObjectsFromArray:temp];
            
            
            [weakSelf cacheMorePictures:temp];
            
            
            
            
        }else{
            
            [weakSelf.tableView.mj_footer endRefreshing];
            
            [SVProgressHUD showInfoWithStatus:error.domain];
            
        }
        
    }];
    
    
    
}


- (void)cacheMorePictures:(NSMutableArray<LifeServiceModel *> *)models{
    
    
    dispatch_group_t group = dispatch_group_create();
    
    for (LifeServiceModel *model in models) {
        
        
        
        dispatch_group_enter(group);
        
        
        [[SDWebImageManager sharedManager] downloadImageWithURL:[NSURL URLWithString:model.image] options:kNilOptions progress:nil completed:^(UIImage *image, NSError *error, SDImageCacheType cacheType, BOOL finished, NSURL *imageURL) {
            
            dispatch_group_leave(group);
            
        }];
        
        
        
    }
    
    
    MJWeakSelf;
    dispatch_group_notify(group, dispatch_get_main_queue(), ^{
        
        if (weakSelf.pageCount.integerValue == self.curpage) {
            
            [weakSelf.tableView.mj_footer endRefreshingWithNoMoreData];
            
        } else {
            
            [weakSelf.tableView.mj_footer endRefreshing];
            
            
        }
        
        
        [weakSelf.tableView reloadData];
        
        
    });
    
    
    
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark - Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    if (self.dataModels == nil) {
        return  0;
    } else {
        return  1;
    }
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    if (self.dataModels == nil) {
        return  0;
    } else {
        
        if (self.dataModels.count == 0) {
            return 1;
        } else {
            return  self.dataModels.count;
        }
        
    }
    
    
}


- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    
    if (self.dataModels.count == 0) {
        
        
        LifeNothingCell *cell = [tableView dequeueReusableCellWithIdentifier:[LifeNothingCell identifierStr]];
        
        
        return cell;
        
        
    } else {
        
        
        LifeServiceCell *cell = [tableView dequeueReusableCellWithIdentifier:[LifeServiceCell identifierStr]];
        
        cell.model = self.dataModels[indexPath.row];
        
        
        return cell;
        
        
    }
    
    
    
}


- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    
    AboutusController *tempVC = [[AboutusController alloc]init];
    
    tempVC.urlString = self.dataModels[indexPath.row].content;
    
    
    [self.navigationController pushViewController:tempVC animated:YES];
    
    
    
}
@end
